/**
 * 关于闭包的测试
 */

var innerfun;
var globalparam = 'baidu';
var FS = require('fs');
var PATH = require('path');
//var colors = require('colors');
var colors = require('colors/safe');
function outfun(param){
    var outparam = 'outparam';
    innerfun = function(){
        console.log(outparam);
        console.log(param);
        console.log(globalparam);
        console.log(globalparam1);
        console.log(outparam1);
    }
    var outparam1 = 'outparam1';
}
var globalparam1 = 'google';

outfun('param');
innerfun();
globalparam1 = 'youtube';
outfun('param1');
innerfun();
function defineClosure(params){
    if(typeof  params ==='object'){
        for(var i in params){
            eval('var '+ i + '=' + params[i]);
        }
    }
    return eval('a+b');
}

//eval('var a={}');
//console.log(a);
var a = 1;
var b = 2;
//console.log(defineClosure());
//console.log(defineClosure({a:4,b:5}));
var fun = defineClosure({a:4,b:5});
//console.log(fun());

console.log(defineClosure({a:4,b:5}));

var fun1 = new Function('return a+b');//error
//console.log(fun1());
/**
 * 从上面的测试可以看出innerfun的闭包包括父内所有变量（即使变量声明在函数定义后面）以及全局中的所有变量
 * 每次调用outfun都会产生一个新的局部闭包而全局闭包相同
 * 使用new Function来定义函数时不会自动定义全局闭包，也就是说代码中的变量需要设置到参数中
 */
/**
 * 使用闭包清除定时器
 * @param times
 */
function print(times){
    var i = 0;
    var id = setInterval(function(){
        i = i + 1;
        if(i >= times){
            clearInterval(id);
        }
        console.log(i);
    },500)
}
//print(2);

function sum(num){
    var sumnum = 0;
    function add(i){
        if(i>num)
            return;
        sumnum = sumnum + i;
        add(i+1);
    }
    add(0);
    return sumnum;
}
console.log(sum(10));
console.log(sum(20));
FS.readdir('.',function(err,files){
    if(err) throw err;
    function file(i){
        if(i>=files.length)
            return;
        var fileName = files[i];
        FS.stat(fileName,function(err,stat){
            if(err) throw err;
            if(stat.isDirectory()){
                console.log('+ '+fileName);
            }else{
                console.log('- '+fileName);
            }
            file(i+1);
        })
    }
    file(0);
    //console.log(files)
})
console.log(colors.green('This is a test'))